package me.khrystal.cleanmaster.base;

import android.app.Activity;
import android.content.Context;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * usage: Activity 栈操作与管理
 * author: kHRYSTAL
 * create time: 16/9/13
 * update time:
 * email: 723526676@qq.com
 */
public class ActivityTask {

    public List<Activity> activityList = new ArrayList<>();

    /**
     * 静态对象 类调用只保存一份
     */
    public static ActivityTask task = new ActivityTask();

    public static ActivityTask getInstance() {
        return task;
    }

    private ActivityTask() {}

    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    public void exit(Context context) {
//        umeng analytics stop record
        MobclickAgent.onKillProcess(context);
        while(activityList.size() > 0) {
            activityList.get(activityList.size() - 1).finish();
        }
        System.exit(0);
    }

    @SuppressWarnings("rawtypes")
    public Activity getActivityByClass(Class clazz) {
        for (Activity a : activityList) {
            if (a.getClass().equals(clazz))
                return a;
        }
        return null;
    }

    public void popActivity(Activity activity) {
        removeActivity(activity);
        activity.finish();
    }

    /**
     * pop activities find one of the clazzs in activityList
     * @param clazzs
     */
    @SuppressWarnings("rawtypes")
    public void popUntilActivity(Class...clazzs) {
        List<Activity> list = new ArrayList<>();
        for (int i = activityList.size()-1; i>=0; i--) {
            Activity a = activityList.get(i);
            boolean isTop = false;
            for (int j = 0; j < clazzs.length; j++) {
                if (a.getClass().equals(clazzs[j])) {
                    isTop = true;
                    break;
                }
            }

            if (!isTop)
                list.add(a);
            else
                break;
        }

        for (Iterator<Activity> iterator = list.iterator(); iterator.hasNext();) {
            Activity activity = iterator.next();
            popActivity(activity);
        }

    }

}
